<template>
  <div style="">
    <Header :left="true" leftText="返回" title="生产领班/品管上班"> </Header>
    <NoticeBar color="#1989fa" background="#ecf9ff" style="margin-top: 5px; font-size: 15px; font-weight: bold"
      left-icon="description">填报信息</NoticeBar>
    <van-form :style="autoHeight" @submit="onSubmit">
      <van-field clearable required v-model="form.plineID" label="生产线选择" class="formstyle" readonly right-icon="scan"
        placeholder="点击扫描设备条码" @click="showScanner">
        <Icon slot="right-icon" center name="enlarge" size="2em"></Icon>
      </van-field>

      <van-field required readonly class="formstyle" label="上班时间" :value="nowDate" @click="showPickerdatetime = true" />
      <van-popup v-model="showPickerdatetime" position="bottom">
        <van-datetime-picker type="date" @confirm="onConfirmdatetime" @cancel="showPickerdatetime = false"
          :min-date="minDate" :max-date="maxDate" :value="currentdate" />
      </van-popup>

      <van-field required readonly class="formstyle" name="picker" :value="valuepShiftName" label="班次选择"
        placeholder="点击选择班次" @click="showPickerpShiftID = true" />
      <van-popup v-model="showPickerpShiftID" position="bottom">
        <van-picker show-toolbar :columns="columnsshift" @confirm="onConfirmpShiftID"
          @cancel="showPickerpShiftID = false">
          <template #option="option">
            <div style="display: flex; flex-direction: column; align-items: center;">
              <div>{{ option.pshiftname }}</div>
            </div>
          </template>
        </van-picker>
      </van-popup>


      <van-field required readonly clickable class="formstyle" name="datetimePicker" :value="form.planworkdatetime"
        label="计划上班时间" placeholder="自动生成" />
      <!-- <van-popup v-model="showPickerdatetime" position="bottom">
        <van-datetime-picker type="datetime" @confirm="onConfirmdatetime" @cancel="showPickerdatetime = false"
          :min-date="minDate" :max-date="maxDate" :value="currentdate" />
      </van-popup> -->


      <!-- <van-field required readonly class="formstyle" name="picker" :value="valueteamName" label="班组选择"
        placeholder="点击选择班组" @click="showPickerteamId = true" />
      <van-popup v-model="showPickerteamId" position="bottom">
        <van-picker show-toolbar :columns="columnsteamId" @confirm="onConfirmteamId" @cancel="showPickerteamId = false">
          <template #option="option">
            <div style="display: flex; flex-direction: column; align-items: center;">
              <div>{{ option.teamName }}</div>
            </div>
          </template>
        </van-picker>
      </van-popup> -->

      <div style="margin: 16px">
        <van-button color="#138087" round block type="info" native-type="submit" @click="gotowork()">打卡上班</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import {
  Col,
  Row,
  Form,
  Cell,
  Icon,
  Field,
  NumberKeyboard,
  Image as VanImage,
  Picker,
  popup,
  SubmitBar,
  Button,
  Loading,
  Overlay,
  Dialog,
  Toast,
  NoticeBar,
  Tag,
  DatetimePicker,
  ImagePreview,
  CellGroup,
  Uploader,
  Cascader,
  Calendar,
  RadioGroup,
  Radio,
  Divider,
  Stepper,
  AddressList,
  Checkbox,
  CheckboxGroup,
} from "vant";

import "vue-easytable/libs/themes-base/index.css";
import { VTable } from "vue-easytable";
import { _httpClient as _httpClientApisie } from "@/libs/apisie";
import { _httpClient as _httpClientApi } from "@/libs/api";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";

Vue.use(Form);
Vue.use(Field);
Vue.use(Overlay);
Vue.use(Loading);
Vue.use(Picker);
Vue.use(popup);
Vue.use(SubmitBar);
Vue.use(VanImage);
Vue.use(DatetimePicker);
Vue.use(Cascader);
Vue.use(Calendar);
Vue.use(Cell);
Vue.use(RadioGroup);
Vue.use(Radio);
Vue.use(Divider);
Vue.use(Stepper);
Vue.use(Button);
Vue.use(AddressList);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Col);
Vue.use(Row);

export default {
  name: "gotoworknew",
  components: {
    Form,
    Row,
    Col,
    Button,
    Header,
    Form,
    Cell,
    Icon,
    Field,
    NumberKeyboard,
    Dialog,
    Toast,
    NoticeBar,
    Row,
    Tag,
    popup,
    DatetimePicker,
    ImagePreview,
    CellGroup,
    Uploader,
    Col,
    Calendar,
    Cascader,
    Picker,
    RadioGroup,
    Radio,
    Divider,
    Stepper,
    VTable,
    AddressList,
    Checkbox,
    CheckboxGroup,
  },
  data() {
    return {
      user: [],
      minDate: new Date(2023, 1, 1),
      maxDate: new Date(2025, 10, 1),
      currentdate: new Date(),
      nowDate: null,
      nowtimer: "",
      form: {
        //班组
        teamId: "",
        //生产线选择
        plineID: "",
        //班次
        pShiftID: "",
        //计划上班时间
        planworkdatetime: "",
        //计划上班时长
        shiftLong: "",
        //计划下班时间
        afterWorkPlanTime: "",
        //在岗状态
        OnPositionFlag: true,
        //工厂代码
        factoryID: ""
      },
      valuepShiftName: "",
      tempTime: "",
      columnsshift: [
      ],
      showPickerpShiftID: false,
      valueteamName: "",
      columnsteamId: [
      ],
      showPickerteamId: false,
      showPickerdatetime: false,
    };
  },

  created: function () {
    this.user = JSON.parse(storage.get("user"));
    this.user.userId = this.user.userName;
    //this.nowtimer = setInterval(this.gettime, 1000);
    //this.getFactoryID();
    api.requestPermission(
      {
        list: ["camera", "microphone", "storage"],
      },
      function (ret, err) { }
    );

    try {
      var manageStorage = api.require("manageStorage");
      manageStorage.getDeviceVersion({}, function (rett) {
        if (Number(rett.version) >= 30) {
          manageStorage.hasAllFilePermission({}, function (ret) {
            if (ret.status == true) {
              return;
            } else {
              manageStorage.requestAllFilePermission({}, function (ret) {});
            }
          });
        } else {
          return;
        }
      });
    } catch {}
    
    this.gettime();
    this.getshift("TC00");
    this.getshiftCUR("TC00");
    this.getteam("TC00");
  },
  destroyed() {
    // clearInterval(this.nowtimer);
    // this.nowDate = null;
  },
  methods: {
    gettime() {
      this.nowDate = new Date().toLocaleDateString().split("/").join('-');;
      //this.form.planworkdatetime = new Date().toLocaleString();
    },
    //确认上班记录
    async gotowork() {
      let _this = this;

      if (_this.form.plineID == "") {
        Toast.fail("请扫描生产线二维码");
        return;
      }
      if (_this.form.planworkdatetime == "") {
        Toast.fail("请选择时间");
        return;
      }
      if (_this.valuepShiftName == "") {
        Toast.fail("请选择班次");
        return;
      }
      // if (_this.valueteamName == "") {
      //   Toast.fail("请选择班组");
      //   return;
      // }
      //this.getAfterWorkPlanTime();
      var bodyss = {
        employeeID: _this.user.userId,
        plineID: _this.form.plineID,
        GotoWorkPlanTime: _this.form.planworkdatetime,
        PShiftID: _this.form.pShiftID,
        PlanWorkTime: _this.form.shiftLong,
        TeamID: "SJT05",
        WorkTimeLong: "0",
        AfterWorkPlanTime: _this.form.afterWorkPlanTime,
        FactoryID: "TC00",
        OnPositionFlag: true
      };
      //alert(JSON.stringify(bodyss));
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      try {
        let res = await _httpClientApisie.post(
          _httpClientApisie.getApiPrefix() + "/EmployeeWorkingRecord/ConfirmWork",
          {
            body: bodyss,
          }
        );
        if (res.Message != null) {
          //message不为空,有报错信息，打卡失败 暂时这样判断
          Toast.clear();
          // Toast.clear();
          Toast.success("打卡成功！");
          api.closeWin();
          this.itemclear();
        } else {
          //打卡成功
          Toast.clear();
          Toast.success("打卡成功！");
          api.closeWin();
          this.itemclear();
        }
      } catch (e) {
        //Toast.fail(JSON.stringify(e));
      }
    },
    //获取工厂信息
    async getFactoryID() {
      let _this = this;
      try {
        _this.user.site = 'TC00';
        _this.getshift(_this.user.site);
        _this.getteam(_this.user.site);
        // let res = await _httpClientApi.get(
        //   _httpClientApi.getApiPrefix() + '/system/ConvertFactoryID/getList/' + _this.user.site,
        // );
        // if (res.code === 200) {        
        //   _this.user.site = '121';
        //   _this.getshift(_this.user.site);
        //   _this.getteam(_this.user.site);
        // }else if(res.code === 403){
        //    Toast.fail("没有权限，请联系管理员授权");
        // }
      } catch (e) {
        //Toast.fail(JSON.stringify(e));
      }
    },
    async getshiftCUR(FactoryID) {
      let _this = this;
      try {
        let res = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() + "/ProductionShift/GetCurrentPShiftBeginEnd?FactoryID=TC00",
        );
        if (res.HttpCode === "200") {
          //alert(res.Data);
          var brg = res.Data.split(";");
          //alert(brg[2]);
          _this.form.planworkdatetime = brg[0].split("/").join('-');;
          //_this.valuepShiftName = _this.columnsshift[0].pshiftname;
          _this.form.pShiftID = brg[2];
        }
      } catch (e) {
        //Toast.fail(JSON.stringify(e));
      }
    },
    //获取班次信息
    async getshift(FactoryID) {
      let _this = this;
      try {
        let res = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() + "/ProductionShift/GetActiveList?Actived=1",
        );
        if (res.HttpCode === "200") {
          //   var brg = res.Data.split(";");
          // }
          for (let index = 0; index < res.Data.length; index++) {
            if (res.Data[index].Actived == false) {
              delete res.Data[index];
            }
          }
          let shiftMap = res.Data.map(item => ({ pshiftname: item.PShiftName + " " + item.BeginTime, pShiftID: item.PShiftID, pShiftTime: item.ShiftLong }))
          _this.columnsshift = shiftMap;
          // if (_this.checkAuditTime('08:30', '20:30')) {
          //   _this.valuepShiftName = _this.columnsshift[0].pshiftname;
          //   _this.form.pShiftID = _this.columnsshift[0].pShiftID;
          // }
          // else {
          //   _this.valuepShiftName = _this.columnsshift[1].pshiftname;
          //   _this.form.pShiftID = _this.columnsshift[1].pShiftID;
          // }
          // _this.BeginTime = _this.columnsshift[0].BeginTime;
        }
      } catch (e) {
        //Toast.fail(JSON.stringify(e));
      }
    },
    checkAuditTime(startTime, endTime) {
      // 获取当前时间
      const date = new Date()
      // 获取当前时间的年月日
      const dataStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} `

      // 获取开始时间、结束时间、现在时间的时间戳
      let startDate = new Date(dataStr + startTime).getTime()
      let endDate = new Date(dataStr + endTime).getTime()
      let nowDate = date.getTime()

      const s = startDate > endDate // 判断开始时间否大于结束时间

      if (s) [startDate, endDate] = [endDate, startDate] // 若开始时间否大于结束时间则交换值

      // 判断现在的时间是否在开始时间和结束时间之间，若s为true则结果取反
      if (nowDate > startDate && nowDate < endDate) {
        return s ? false : true
      } else {
        return s ? true : false
      }
    },
    //获取班组信息
    async getteam(FactoryID) {
      let _this = this;
      try {
        let res = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() + "/Team/GetList?FactoryID=" + FactoryID,
        );
        if (res.HttpCode === "200") {
          let teamMap = res.Data.map(item => ({ teamId: item.TeamID, teamName: item.TeamName }))
          _this.columnsteamId = teamMap;
          _this.valuepShiftName = this.columnsshift[0].pshiftname;
          _this.form.pShiftID = this.columnsshift[0].pShiftID;
          _this.form.shiftLong = this.columnsshift[0].pShiftTime;
        }
      } catch (e) {
        //Toast.fail(JSON.stringify(e));
      }
    },
    //打开扫描
    showScanner() {
      let _this = this;
      if (
        api.deviceName.toLowerCase() == "huawei" ||
        api.deviceName.toLowerCase() == "honor"
      ) {
        //_this.form.plineID = ret.content ;

        var zyHmsScan = api.require('zyHmsScan');
        var param = {
          //returnAll:true
        };
        zyHmsScan.openDefaultView(param, function (ret) {
          _this.form.plineID = ret.result;
          //api.alert({ msg: JSON.stringify(ret) });
        });
        // var QRScan = api.require("QRScan");
        // QRScan.customizedScanner(
        //   {
        //     rect: {
        //       x: 0, //（可选项）数字类型；模块左上角的 x 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       y: 0, //（可选项）数字类型；模块左上角的 y 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       w: 320, //（可选项）数字类型；模块的宽度；支持设置'auto'；默认：所属的 Window 或 Frame 的宽度
        //       h: 480, //（可选项）数字类型；模块的高度；支持设置'auto'；默认：所属的 Window 或 Frame 的高度
        //     },
        //     rectOfInterest: {
        //       x: 64, //（可选项）数字类型；扫码识别区域左上角的 x 坐标（相对于扫码区rect）；默认：0
        //       y: 65, //（可选项）数字类型；扫码识别区域左上角的 y 坐标（相对于扫码区rect）；默认：0
        //       w: 250, //（可选项）数字类型；扫码识别区域的宽度；默认：扫码区rect的宽度
        //       h: 250, //（可选项）数字类型；扫码识别区域的高度；默认：扫码区rect的高度
        //     },
        //     //tipString:'放入框内扫码',
        //     maskColor: "rgba(0,0,0,0.5)",
        //     scanLine: {
        //       color: "#00FF00",
        //       thickness: 2,
        //     },
        //     marginB: 30,
        //     formatType: "ALL",
        //   },
        //   function (ret) {
        //     if (ret) {
        //       // if (_this.form.plineID.indexOf(ret.content) != -1) {
        //       //   Toast.fail("已扫描");
        //       // }
        //       // else {
        //         _this.form.plineID = ret.content ;//+ "," + _this.form.plineID;
        //       //}
        //       // _this.form.plineID= _this.form.plineID.substring(0, _this.form.plineID.lastindexof(','));
        //     }
        //   }
        // );
        //QRScan.closeCustomizedScanner();
      } else {
        var FNScanner = this.$ac.require("FNScanner");
        FNScanner.openScanner(
          {
            autorotation: true,
          },
          function (ret, err) {
            if (ret) {
              if (ret.eventType == "success" && ret.content != "") {
                // if (_this.form.plineID.indexOf(ret.content) != -1) {
                //   Toast.fail("已扫描");
                // }
                // else {
                _this.form.plineID = ret.content;//+ "," + _this.form.plineID;
                //}
                //_this.form.plineID= _this.form.plineID.substring(0, _this.form.plineID.lastindexof(','));
              }
            } else {
              //alert(JSON.stringify(err));
            }
          }
        );
      }
    },
    itemclear() {
      this.form.plineID = "";
      this.valuepShiftName = "";
      this.form.pShiftID = "";
      this.valueteamName = "";
      this.form.planworkdatetime = "";
      this.form.teamId = "";
      this.tempTime = "";
    },
    onConfirmteamId(value, index) {
      this.form.teamId = this.columnsteamId[index].teamId;
      this.valueteamName = this.columnsteamId[index].teamName;
      this.showPickerteamId = false;
    },
    onConfirmpShiftID(value, index) {
      this.valuepShiftName = this.columnsshift[index].pshiftname;
      this.form.pShiftID = this.columnsshift[index].pShiftID;
      this.form.shiftLong = this.columnsshift[index].pShiftTime;
      this.showPickerpShiftID = false;
      //alert(this.form.pShiftID);
      //早班
      //new Date().toLocaleDateString().replace("/", "-");
      // var nowstr = new Date().toLocaleDateString().split("/").join('-');
      // var tomorrow = new Date(today);
      // tomorrow.setDate(today.getDate() + 1);
      // var tomorrowstr =tomorrow.toLocaleDateString().split("/").join('-');
      // alert(this.form.pShiftID);
      // alert(nowstr);
      // alert(tomorrowstr);
      let dateTime;
      let dateTime1;
      let yy = new Date(this.nowDate).getFullYear();
      let mm = new Date(this.nowDate).getMonth() + 1;
      let dd = new Date(this.nowDate).getDate();
      let dd1 = new Date(this.nowDate).getDate() + 1;
      let hh = new Date(this.nowDate).getHours();
      let mf =
        new Date(this.nowDate).getMinutes() < 10
          ? "0" + new Date(this.nowDate).getMinutes()
          : new Date(this.nowDate).getMinutes();
      let ss =
        new Date(this.nowDate).getSeconds() < 10
          ? "0" + new Date(this.nowDate).getSeconds()
          : new Date(this.nowDate).getSeconds();
      dateTime = yy + "-" + mm + "-" + dd + " ";
      dateTime1 = yy + "-" + mm + "-" + dd1 + " ";

      if (this.form.pShiftID == "BC01") {
        // alert(1);
        this.form.planworkdatetime = dateTime + " 08:30:00";
      }
      //夜班
      if (this.form.pShiftID == "BC02") {
        // alert(2);
        this.form.planworkdatetime = dateTime + " 20:30:00";
      }
      //倒班-早班
      if (this.form.pShiftID == "BC03") {
        // alert(3);
        this.form.planworkdatetime = dateTime + " 08:30:00";
      }
      //倒班-中班
      if (this.form.pShiftID == "BC04") {
        // alert(4);
        this.form.planworkdatetime = dateTime + " 16:30:00";
      }
      //倒班-夜班
      if (this.form.pShiftID == "BC05") {
        ///alert(5);
        this.form.planworkdatetime = dateTime1 + " 00:30:00";
      }
    },
    onConfirmdatetime(time) {
      this.tempTime = time;
      //date.setMinutes(date.getMinutes() - date.getTimezoneOffset()); // 时区补偿
      this.nowDate = `${time.getFullYear()}-${time.getMonth() + 1
        }-${time.getDate()}`;
      this.showPickerdatetime = false;
    },
    getAfterWorkPlanTime() {
      let shiftLong = this.form.shiftLong;
      let min = this.tempTime.getMinutes()
      this.tempTime.setMinutes(min + shiftLong)
      this.form.afterWorkPlanTime = `${this.tempTime.getFullYear()}-${this.tempTime.getMonth() + 1
        }-${this.tempTime.getDate()} ${this.tempTime.getHours().toString().padStart(2, 0)}:${this.tempTime
          .getMinutes()
          .toString()
          .padStart(2, 0)}`;
    }
  },
};
</script>

<style>
body {
  background-color: white;
}

.table-title-class {
  background-color: #304156;
  color: #fff;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.buttongroup {
  float: right;
  margin-right: 10px;
  margin-top: 10px;
  margin-bottom: 20px;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: center;
}

.buttonLeft {
  position: fixed;
  bottom: 8px;
  float: left;
  width: 49%;
}

.formstyle {
  margin-top: 8px;
  font-size: 15px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.radioteam {
  display: flex;
  align-items: center;
  padding-left: 13px;
  margin-top: 10px;
  margin-left: 34px;
  margin-bottom: 10px;
}

.buttonRight {
  position: fixed;
  bottom: 8px;
  float: right;
  left: 51%;
  width: 49%;
  background-color: #f22028;
  border-color: #f22028;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 50%;
  bottom: 3rem;
  overflow: scroll;
  right: 10px;
  width: 100%;
  z-index: 1;
}

.message {
  font-size: 15px;
  margin-top: 5px;
  margin-left: -10px;
  font-weight: bold;
}

.mg5 {
  margin-right: 5px;
}

.tag_margin {
  margin: 2px 5px;
}

.card_under {
  height: 100%;
  width: 100%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0.3);
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #4e4a67;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.text_small {
  font-size: 16px;
  color: red;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 700;
}

.text_scan {
  font-size: 16px;
  color: #4e4a67;
  margin: auto auto auto 20px;
  line-height: 1.5em;
  text-align: justify;
}

.divStyle {
  margin-left: 3px;
  margin-right: 3px;
}
</style>
